package com.syqc.choose.team

import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.AppContext
import com.syqc.entity.TeamInfo
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import io.reactivex.rxjava3.subjects.PublishSubject
import kotlin.concurrent.thread

/**
 *@Author Jasper
 *@Time   2020/10/30
 *@Desc   车队选择
 */
class ChooseTeamViewModel : AutoDisposeViewModel() {
    private var pid = "0"
    val pids = mutableListOf<String>()

    //当前车对下的子车队
    private val teams by lazy { ArrayList<TeamInfo>() }

    private val allTeams by lazy { ArrayList<TeamInfo>() }

    //搜索车辆
    private val searchTeams by lazy { ArrayList<TeamInfo>() }

    var isRootTeam = MutableLiveData<Boolean>()

    //非0根节点集合
    private val roots by lazy {
        ArrayList<String>()
    }

    //
    private val teamMap by lazy {
        HashMap<String, TeamInfo>()
    }
    private val teamChildsMap by lazy {
        HashMap<String, MutableList<String>>()
    }

    val teamsSub by lazy {
        PublishSubject.create<MutableList<TeamInfo>>()
    }

    val searchTeamsSub by lazy {
        PublishSubject.create<MutableList<TeamInfo>>()
    }
    val teamTitleSub by lazy {
        PublishSubject.create<String>()
    }

    fun getAllTeam() {
        isRootTeam.postValue(true)
        toastLoading(true)
        ServiceHelper.getRepository().getTeams().autoDispose(this).subscribe({
            toastLoading(false)
            if (it.isNullOrEmpty()) {
                toast(R.string.toast_no_team)
                return@subscribe
            }
            thread { handleTeams(it) }
            allTeams.clear()
            allTeams.addAll(it)
            searchTeamsSub.onNext(allTeams)
        }, error)
    }

    /**
     * 处理车队
     */
    private fun handleTeams(entitys: MutableList<TeamInfo>) {
        val allTeamIds = ArrayList<String>()
        for (entity in entitys) {
            //存入数据 所有的车队信息
            teamMap[entity.teamId] = entity
            //根据pid存入相同父类车队
            val childTeams = teamChildsMap[entity.pid] ?: ArrayList<String>()
            childTeams.add(entity.teamId)
//            Logger.e("${entity.pid}    $childTeams")
            teamChildsMap[entity.pid] = childTeams
            allTeamIds.add(entity.teamId)
        }
        //判断是否存在非0pid
        for (teamItem in entitys) {
            if (!allTeamIds.contains(teamItem.pid)) {
                roots.add(teamItem.teamId)
            }
        }
        pids.clear()
        teamTitle()
        getTeamsById(pid)
    }

    //上一级
    fun previousTeam() {
        if (pids.size <= 1) {
            toast(R.string.desc_root_team)
            return
        }
        if (pid == "0") {
            teamTitle()
            return
        }
        pids.removeAt(pids.lastIndex)
        pid = pids.last()

        if (pid == "0") {
            teamTitle()
            isRootTeam.postValue(true)
        }
        teamTitleSub.onNext(
            teamMap[pid]?.teamName ?: AppContext.getDescById(R.string.desc_choose_root)
        )
        getTeamsById(pid, true)

    }

    //根车队
    fun rootTeam() {
        if (pids.size <= 0 || pid == "0") {
            toast(R.string.desc_root_team_)
            return
        }
        pids.clear()
        pid = "0"
        getTeamsById(pid)
        isRootTeam.postValue(true)
        teamTitle()
    }

    private fun teamTitle() {
        teamTitleSub.onNext(AppContext.getDescById(R.string.desc_choose_root))
    }


    fun getTeamsById(teamId: String, isPrevious: Boolean = false) {
        val childTeamIds = if (teamId == "0") roots else teamChildsMap[teamId]
        if (childTeamIds.isNullOrEmpty()) {
            toast(R.string.toast_no_child_team)
        } else {
            teams.clear()
            if (!isPrevious) {
                pid = teamId
                pids.add(teamId)
                if (teamId != "0") isRootTeam.postValue(false)
            }
            for (childId in childTeamIds) {
                teams.add(teamMap[childId]!!)
            }
            teamsSub.onNext(teams)
        }
    }

    // 查询车队
    fun searchTeam(key: String) {

        if (allTeams.isNullOrEmpty()) {
            toast(R.string.toast_no_team)
            return
        }
        val upKey = key.uppercase()
        searchTeams.clear()
        for (team in allTeams) {
            if (team.teamName.uppercase().contains(upKey)) searchTeams.add(team)
        }

        searchTeamsSub.onNext(searchTeams)
    }
}
